'use strict'

import axios from 'axios'
import qs from 'qs'
import {baseURL} from './url'
import config from './config'
import { getStore } from '../utils/saveUtil'

axios.interceptors.request.use(config => {
  return config
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.resolve(error.response)
})

function checkStatus (response) {
  // 判断toke是否失效
  if (response && response.data.code === 999) {
    alert('请在小业务系统登录')
  }
  // 如果http状态码正常，则直接返回数据
  if (response) {
    return response
  }
  return {// 这里已经包括网络错误，服务器错误，后端抛出的错误，可以弹出一个错误提示，告诉用户
    data: {
      code: config.ERROR_CODE,
      msg: '网络异常！'
    }
  }
}

function checkCode (res, url, params) {
  if (res.data) res = res.data
  if (res.code || res.code !== 0) {
    // 异常监控上报
    // uploadLog(res, url, params)
    try {
      res.msg = res.msg ? res.msg : '网络异常！'
    } catch (e) {
      res = {
        code: config.ERROR_CODE,
        msg: '网络异常！'
      }
    }
  }
  return res
}

// function uploadLog (res, url, send_params) {
//
// }

export default {
  post (url, params) {
    for (let i in params) { // 解决php后台无法读取收据
      if (params.hasOwnProperty(i) && typeof params[i] !== 'function') {
        if (typeof (params[i]) === 'object') {
          params[i] = JSON.stringify(params[i])
        }
      }
    }
    return axios({
      headers: {
        'Authorization': 'Bearer ' + getStore('userToken')
      },
      method: 'post',
      baseURL: baseURL,
      url,
      data: qs.stringify(params),
      timeout: 10000
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res, url, params)
      }
    )
  },

  get (url, params) {
    return axios({
      headers: {
        'Authorization': 'Bearer ' + getStore('userToken')
      },
      method: 'get',
      baseURL: baseURL,
      url,
      params,
      timeout: 10000
    }).then(
      (response) => {
        return checkStatus(response)
      }
    ).then(
      (res) => {
        return checkCode(res, url, params)
      }
    )
  }
}
